package com.java.shop.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.constant.WareConstant;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;
import com.java.shop.ware.dao.PurchaseDao;
import com.java.shop.ware.entity.PurchaseDetailEntity;
import com.java.shop.ware.entity.PurchaseEntity;
import com.java.shop.ware.service.PurchaseDetailService;
import com.java.shop.ware.service.PurchaseService;
import com.java.shop.ware.service.WareSkuService;
import com.java.shop.ware.vo.MergePurchaseVo;
import com.java.shop.ware.vo.ProductToWareVo;
import com.java.shop.ware.vo.PurchaseDoneItemVo;
import com.java.shop.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getUnreceiveList(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wr = new QueryWrapper<>();
        wr.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wr
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购需求为采购单
     * @param mergeVo
     */
    @Transactional
    @Override
    public void mergePurchase(MergePurchaseVo mergeVo) {//如果采购订单存在则合并到采购订单，不存在则新建一张采购订单并将采购需求合并到该订单上
        Long purchaseId = mergeVo.getPurchaseId();
        if(purchaseId == null){
            //采购单不存在新建
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEunm.CREATE.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();

        }

        //确认采购单的状态是0或1
        PurchaseEntity entity = this.getById(purchaseId);
        Integer status = entity.getStatus();
        if(status == WareConstant.PurchaseStatusEunm.CREATE.getCode() || status == WareConstant.PurchaseStatusEunm.ASSIGNED.getCode()){
            //将采购项合并为采购单
            List<Long> items = mergeVo.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = items.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item);
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEunm.ASSIGNED.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect);
        }
    }

    @Override
    public void receivedPurchase(List<Long> ids) {
        //1.确定采购单是否是新建或已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEunm.CREATE.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEunm.ASSIGNED.getCode()) return true;
            return false;
        }).map(item->{
            item.setStatus(WareConstant.PurchaseStatusEunm.RECEIVE.getCode());
            return item;
        }).collect(Collectors.toList());

        //2.改变采购单的状态
        this.updateBatchById(collect);


        //3.改变采购项的状态
        collect.forEach(item->{
            List<PurchaseDetailEntity> list = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> collect1 = list.stream().map(detailEntity -> {
                //免更新其他数据
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(detailEntity.getId());
                entity.setStatus(WareConstant.PurchaseDetailStatusEunm.BUYING.getCode());
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);
        });
    }


    @Override
    public void done(PurchaseDoneVo doneVo) {

        //2.改变采购项状态
        Boolean flag = true;
        ArrayList<PurchaseDetailEntity> list = new ArrayList<>();
        List<PurchaseDoneItemVo> items = doneVo.getItems();
        for(PurchaseDoneItemVo item : items){
            PurchaseDetailEntity detailEntry = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEunm.HASERROR.getCode()){
                flag = false;
                detailEntry.setStatus(item.getStatus());
            }else{
                detailEntry.setStatus(WareConstant.PurchaseDetailStatusEunm.FINISH.getCode());
                //3.将成功采购的商品纳入库存
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                ProductToWareVo wareVo = new ProductToWareVo();
                wareVo.setSkuId(entity.getSkuId());
                wareVo.setWareId(entity.getWareId());
                wareVo.setStock(entity.getSkuNum());
                wareSkuService.addStock(wareVo);

            }
            detailEntry.setId(item.getItemId());
            list.add(detailEntry);
        }
        purchaseDetailService.updateBatchById(list);


        //1.改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVo.getId());
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEunm.FINISH.getCode():WareConstant.PurchaseStatusEunm.HASERROR.getCode());
        this.updateById(purchaseEntity);


    }
}